package com.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mypg.Info;
import com.mypg.InfoHelper;
import com.mypg.News;
import com.mypg.NewsHelper;
import com.service.NewsService;
import org.apache.commons.fileupload.util.Streams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RequestMapping("/news")
@Controller
public class NewsController {

    @Autowired
    NewsService newsService;

    @RequestMapping("/news_table_select.do")
    @ResponseBody
    public String doNews_table_select(String news_class, String time_start, String time_end,
                                               int page, int limit) throws ParseException, JsonProcessingException {
        int start_row=(page-1)*limit;
        int page_nums=limit;
        Timestamp timestamp_start;
        Timestamp timestamp_end;
        SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm");
        if(time_start==null||time_start==""){
            time_start="1970-01-01 01:01";
            timestamp_start=new Timestamp(df.parse(time_start).getTime());
        }else{
            timestamp_start=new Timestamp(df.parse(time_start).getTime());
        }

        if(time_end==null||time_end==""){
            timestamp_end=new Timestamp(System.currentTimeMillis());
        }else{
            timestamp_end=new Timestamp(df.parse(time_end).getTime());
        }
        HashMap<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",newsService.selectNews_count_For_news_table_jsp(news_class,timestamp_start,timestamp_end));
        List<News> newsList=newsService.selectNewsFor_news_table_jsp(news_class,timestamp_start,timestamp_end,start_row,page_nums);
        map.put("data", NewsHelper.changeNewsListToNewsHelperList(newsList));
        ObjectMapper mapper=new ObjectMapper();
        String map_json_str=mapper.writeValueAsString(map);
        return map_json_str;
    }

    @RequestMapping("/news_table_delete_one.do")
    @ResponseBody
    public void doNews_table_delete_one(int news_id,HttpSession session){
        String path= (String) session.getAttribute("img_save_path");
        path+="/news_img/";
        News news=newsService.selectNewsByNews_id(news_id);
        File file=new File(path+news.getNews_img());
        file.delete();
        newsService.deleteNewsByNews_id(news_id);
    }

    @RequestMapping("/news_table_delete_many.do")
    @ResponseBody
    public int doNews_table_delete_many(String[] news_id_array,HttpSession session){
        news_id_array[0]=news_id_array[0].replace("[","");
        news_id_array[news_id_array.length-1]=news_id_array[news_id_array.length-1].replace("]","");
        String path= (String) session.getAttribute("img_save_path");
        path+="/news_img/";
        for(int i=0;i<news_id_array.length;i++){
            News news=newsService.selectNewsByNews_id(Integer.parseInt(news_id_array[i]));
            File file=new File(path+news.getNews_img());
            file.delete();
            newsService.deleteNewsByNews_id(Integer.parseInt(news_id_array[i]));
        }
        return 0;
    }

    @RequestMapping("/news_table_add_with_file.do")
    @ResponseBody
    public Map<String,Object> doNews_table_add_with_file(String news_title, String news_content, String news_class,
                                           @RequestParam(value="file_content",required = false) MultipartFile file_content,
                                           @RequestParam(value="file_img",required = false) MultipartFile file_img,
                                           HttpSession session){
        News news=new News();
        String content_to_upload="";
        String img_to_upload="";

        if(file_content==null){
            content_to_upload=news_content;
        }else{
            if(!file_content.isEmpty()){
                try {
                    InputStream in = file_content.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
                    int a = 0;
                    while((a = bufferedReader.read())!=-1){
                        char ch=(char)a;
                        content_to_upload+=ch;
                    }
                    in.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        if(file_img==null){
            img_to_upload="";
        }else{
            img_to_upload=UUID.randomUUID()+"_with_"+file_img.getOriginalFilename();
            String path= (String) session.getAttribute("img_save_path");
            path+="/news_img/";
            if(!file_img.isEmpty()){
                try {

                    File uploadFile=new File(path+img_to_upload);
                    Streams.copy(file_img.getInputStream(),new FileOutputStream(uploadFile.getAbsolutePath()),true);


//                    FileOutputStream fos = new FileOutputStream(path + img_to_upload);
//                    InputStream in = file_img.getInputStream();
//                    int a = 0;
//                    while((a = in.read())!=-1){
//                        fos.write(a);
//                    }
//                    in.close();
//                    fos.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        Timestamp timestamp=new Timestamp(System.currentTimeMillis());
        news.setNews_title(news_title);
        news.setNews_content(content_to_upload);
        news.setNews_img(img_to_upload);
        news.setNews_time(timestamp);
        news.setNews_class(news_class);
        newsService.insertNews(news);
        HashMap<String,Object> map=new HashMap<>();
        map.put("str",content_to_upload);
        return map;
    }

    @RequestMapping("/news_table_edit.do")
    @ResponseBody
    public Map<String, Object> doNews_table_edit(int news_id, String news_title, String news_content, String news_class,
                                                 @RequestParam(value="file_content",required = false) MultipartFile file_content) throws JsonProcessingException {
        String content_to_upload="";
        if(file_content==null){
            content_to_upload=news_content;
        }else{
            if(!file_content.isEmpty()){
                try {
                    InputStream in = file_content.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
                    int a = 0;
                    while((a = bufferedReader.read())!=-1){
                        char ch=(char)a;
                        content_to_upload+=ch;
                    }
                    in.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        News news=new News();
        news.setNews_id(news_id);
        news.setNews_title(news_title);
        news.setNews_content(content_to_upload);
        news.setNews_class(news_class);
        newsService.updateNewsByNews_id(news);
        HashMap<String,Object> map=new HashMap<>();
        map.put("str",content_to_upload);
        return map;
    }

    @RequestMapping("/news_table_edit_init.do")
    @ResponseBody
    public News doNews_table_edit_init(int news_id){
        return newsService.selectNewsByNews_id(news_id);
    }

    @RequestMapping("/news_table_edit_upload_img.do")
    @ResponseBody
    public String doNews_table_edit_upload_img(@RequestParam(value="file",required = false) MultipartFile file_img,
                                               HttpSession session, int news_id) throws JsonProcessingException {
        HashMap<String, Object> map = new HashMap<>();
        if(session.getAttribute("flag_manager")!=null) {
            String img_to_upload = "";
            img_to_upload = UUID.randomUUID() + "_with_" + file_img.getOriginalFilename();
            String path = (String) session.getAttribute("img_save_path");
            path += "/news_img/";
            String news_img = newsService.selectNewsByNews_id(news_id).getNews_img();
            if (file_img != null) {
                if (!file_img.isEmpty()) {
                    File file = new File(path + news_img);
                    file.delete();
                    try {

                        File uploadFile = new File(path + img_to_upload);
                        Streams.copy(file_img.getInputStream(), new FileOutputStream(uploadFile.getAbsolutePath()), true);


//                    FileOutputStream fos = new FileOutputStream(path + img_to_upload);
//                    InputStream in = file_img.getInputStream();
//                    int a = 0;
//                    while ((a = in.read()) != -1) {
//                        fos.write(a);
//                    }
//                    in.close();
//                    fos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    newsService.updateNews_imgByNews_id(img_to_upload, news_id);
                }

            }

            map.put("code", 0);
            map.put("msg", "");
            map.put("data", img_to_upload);
        }else{
            map.put("code", 0);
            map.put("msg", "");
            map.put("data", "fail");
        }
        return new ObjectMapper().writeValueAsString(map);
    }
}
